using AutoMapper;
using BaseData.WriteApi.Appcontext.Command.Initialform_Files;
using MediatR;
using SmartTracking.Domain.HQX;
using SmartTracking.ErrorCode;
using SmartTracking.Infrastructure.Interfaces;
using Yitter.IdGenerator;

namespace BaseData.WriteApi.Appcontext.CommandHandler.Initialform_Files
{
    /// <summary>
    /// 初期表单批量创建命令处理器
    /// </summary>
    public class CreateInitialformBatchCommandHandler : IRequestHandler<CreateInitialformBatchCommand, ApiResult<List<int>>>
    {
        private readonly IBaseRepository<Initialform> _initialformRepository;
        private readonly IMapper _mapper;
        private readonly ILogger<CreateInitialformBatchCommandHandler> _logger;

        public CreateInitialformBatchCommandHandler(
            IBaseRepository<Initialform> initialformRepository,
            IMapper mapper,
            ILogger<CreateInitialformBatchCommandHandler> logger)
        {
            _initialformRepository = initialformRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理初期表单批量创建命令
        /// </summary>
        /// <param name="request">批量创建命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>创建结果</returns>
        public async Task<ApiResult<List<int>>> Handle(CreateInitialformBatchCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<List<int>> { data = new List<int>() };
            
            try
            {
                #region 参数验证
                if (request == null)
                {
                    _logger.LogWarning("初期表单批量创建请求参数为空");
                    return new ApiResult<List<int>> { Code = ApiEnum.新增失败, Message = "请求参数不能为空", data = new List<int>() };
                }

                    if (request.SheepIds == null || !request.SheepIds.Any())
                    {
                        _logger.LogWarning("羊只Id列表为空");
                        return new ApiResult<List<int>> { Code = ApiEnum.新增失败, Message = "羊只Id列表不能为空", data = new List<int>() };
                    }

                    if (request.InitialGenders == null || !request.InitialGenders.Any())
                    {
                        _logger.LogWarning("初期性别列表为空");
                        return new ApiResult<List<int>> { Code = ApiEnum.新增失败, Message = "初期性别列表不能为空", data = new List<int>() };
                    }

                    if (request.SheepIds.Count != request.InitialGenders.Count)
                    {
                        _logger.LogWarning($"羊只Id数量({request.SheepIds.Count})与性别数量({request.InitialGenders.Count})不匹配");
                        return new ApiResult<List<int>> { Code = ApiEnum.新增失败, Message = "羊只Id数量与性别数量必须一致", data = new List<int>() };
                    }

                    if (request.SheepIds.Count > 1000)
                    {
                        _logger.LogWarning($"批量创建数量超过限制: {request.SheepIds.Count}");
                        return new ApiResult<List<int>> { Code = ApiEnum.新增失败, Message = "批量创建数量不能超过1000条", data = new List<int>() };
                    }

                    // 验证羊只Id是否重复
                    var duplicateIds = request.SheepIds.GroupBy(x => x).Where(g => g.Count() > 1).Select(g => g.Key).ToList();
                    if (duplicateIds.Any())
                    {
                        _logger.LogWarning($"羊只Id重复: {string.Join(",", duplicateIds)}");
                        return new ApiResult<List<int>> { Code = ApiEnum.新增失败, Message = $"羊只Id不能重复: {string.Join(",", duplicateIds)}", data = new List<int>() };
                    }
                    #endregion

                    #region 数据准备
                    var initialformEntities = new List<Initialform>();
                    var addedIds = new List<int>();

                    // 如果单据号为空，使用雪花ID生成基础单据号
                    var baseDocumentNumber = request.DocumentNumber ?? YitIdHelper.NextId().ToString();

                    for (int i = 0; i < request.SheepIds.Count; i++)
                    {
                        var sheepId = request.SheepIds[i];
                        var gender = request.InitialGenders[i];

                        // 验证羊只Id有效性
                        if (sheepId <= 0)
                        {
                            throw new ArgumentException($"羊只Id无效: {sheepId}");
                        }

                        // 验证性别值有效性（1=公，2=母）
                        if (gender != 1 && gender != 2)
                        {
                            throw new ArgumentException($"性别值无效: {gender}，必须为1(公)或2(母)");
                        }

                        // 生成包含羊只Id的单据号
                        var documentNumber = $"{baseDocumentNumber}_{sheepId}";

                        var entity = new Initialform
                        {
                            DocumentNumber = documentNumber,
                            InitialGender = gender,
                            SheepId = sheepId,
                            Note = request.Note ?? string.Empty
                        };

                        initialformEntities.Add(entity);
                    }
                    #endregion

                #region 批量添加
                _logger.LogInformation($"开始批量创建初期表单，数量: {initialformEntities.Count}");
                
                await _initialformRepository.AddRangeAsync(initialformEntities);
                
                // 获取新增的ID列表
                addedIds = initialformEntities.Select(x => x.InitialId).ToList();
                
                _logger.LogInformation($"批量创建初期表单成功，共创建: {addedIds.Count} 条记录");
                #endregion

                #region 发布事件
                // 发布批量创建完成事件
                var batchEvent = new InitialformBatchCreatedEvent
                {
                    CreatedIds = addedIds,
                    CreatedCount = addedIds.Count,
                    CreatedTime = DateTime.Now
                };
                
                // 这里可以发布事件，如果使用了事件总线
                // await _eventPublisher.PublishAsync(batchEvent);
                _logger.LogInformation($"发布初期表单批量创建事件，创建数量: {batchEvent.CreatedCount}");
                #endregion

                result.Code = ApiEnum.新增成功;
                result.Message = $"批量创建成功，共创建 {addedIds.Count} 条记录";
                result.data = addedIds;
                
                return result;
            }
            catch (ArgumentException ex)
            {
                _logger.LogWarning($"参数验证异常: {ex.Message}");
                return new ApiResult<List<int>> { Code = ApiEnum.新增失败, Message = ex.Message, data = new List<int>() };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"批量创建初期表单时发生系统异常: {ex.Message}");
                return new ApiResult<List<int>> { Code = ApiEnum.新增失败, Message = "系统异常，请联系管理员", data = new List<int>() };
            }
        }
    }

    /// <summary>
    /// 初期表单批量创建完成事件
    /// </summary>
    public class InitialformBatchCreatedEvent
    {
        /// <summary>
        /// 创建的ID列表
        /// </summary>
        public List<int> CreatedIds { get; set; } = new List<int>();
        
        /// <summary>
        /// 创建数量
        /// </summary>
        public int CreatedCount { get; set; }
        
        /// <summary>
        /// 创建时间
        /// </summary>
        public DateTime CreatedTime { get; set; }
    }
}